﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AsPlugInManager;
using AsLib;

namespace NNLInterface
{
    public partial class frmProcessCard : NNLInterface.frmBaseBasic
    {
         #region 初始化

        private string strDeptNo;
        string strTranNo = "";
        string strGroupNo = "";
        string DeptNo = "";
        string resCode = "";
        string strStartTime = "";
        string strEndTime = "";
        string ItemID;

       //报表数据源
        DataTable dtOrder;
    

        public frmProcessCard()
        {
            InitializeComponent();
        }


        public frmProcessCard(IASPArgList argList)  
        {
            InitializeComponent();
            //this.ImportButtonVisibility = false;
            this.SowCheckBox = true;
            this.CmdImport.Caption = "报表预览";
            this.PrintButtonVisibility = true;
            this.lokDepart.EditValueChanged += new EventHandler(lokDepart_EditValueChanged);
            this.lokDepart.ProcessNewValue += new DevExpress.XtraEditors.Controls.ProcessNewValueEventHandler(lokDepart_ProcessNewValue);
            this.ListGrid.MouseDown += new MouseEventHandler(ListGrid_MouseDown);

        }

        void frmProcessCard_Load(object sender, EventArgs e)
        {
            //如果当前工程下的用户名为空，则提示输入
            if (common._userid == "")
            {
                frmLogon frmLog = new frmLogon();
                frmLog.ShowDialog();

                if (frmLog.DialogResult == DialogResult.OK)
                {
                    frmLog.Dispose();
                    frmLog = null;
                }
                else
                {
                    this.Close();
                    return;
                }

            }

            IniDataSource();
        }


        private void IniDataSource()
        {
            this.txtUser.Text = common._userid;
            this.txtUserName.Text = common._username;
            this.txtDeptNo.Text = common._DeptNo;
            this.txtDeptName.Text = common._DeptName;

            lokPlanNo.Properties.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.Never;
            lokDepart.Properties.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.Never;


            //设定部门的数据源
            SetDeptDataSource();

            //显示订单数据
            string strSQL = "select   cast(0 as bit) as chkSelect ,  Code, ItemCode, dbo.GetShortDate( EST) est,"
                           + " dbo.GetShortDate( LET) let, Qty, dbo.GetShortDate(starttime) starttime,"
                           + " dbo.GetShortDate(endtime) endtime, Spec1Code,CustomerCode,1 as showTZ,"
                           + " Spec2Code,bb.PrintCount,cast('' as nvarchar(1000)) picPath,"
                           //2012-04-05显示订单的ChildCode字段中的第一个工序的资源代码
                           + " (SELECT DISTINCT oz.OperationMainResCode "
                           + " FROM OperationZ1 oz WHERE oz.TranNo=aa.TranNo AND   oz.ordercode=aa.Code "
                           + " and oz.procno=left(aa.childcode,2) ) Resource "
                           + " FROM OrdersOutZ1 aa "
                           + " left outer join ProcesCardPrint" + common._userid + " bb  on aa.code=bb.MoNo"
                           + " where 1=2 ";
            common.SubShowList(accessdb.GetRecord(strSQL).ADODataRst, this.ListGrid, this.ListView, false);
            common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
            this.ListView.Columns[0].OptionsColumn.AllowEdit = true;

            //设定显示图纸按钮控件
            DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit repProLotNo = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            repProLotNo.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            repProLotNo.Buttons[0].Caption = "查看图纸";
            repProLotNo.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            this.ListView.Columns["showTZ"].ColumnEdit = repProLotNo;
            this.ListView.Columns["showTZ"].Width = 100;
            repProLotNo.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(repProLotNo_ButtonClick);
            this.ListView.Columns["showTZ"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;

            //初始化日期
            string strDepartNo = common.pro.GetAsStr((TPropertyID)Convert.ToInt32(common.GetLanguageWord("PropertyID", "ProjectUser_DepartNo")), 1);

            //设定版本号
            //strSQL =string.Format( "SELECT DISTINCT o.TranNo FROM Operation" + common._userid + " o ORDER BY o.TranNo desc",strDepartNo);
            //DataTable dt=accessdb.GetRecord(strSQL).ADODataRst;
            //this.lokPlanNo.Properties.DataSource =dt; 
            //if (dt.Rows.Count>=1)
            //{
            //    this.lokPlanNo.Text = dt.Rows[0][0].ToString();
            //    this.lokPlanNo.EditValue = dt.Rows[0][0].ToString();
            //}

            
            common.GetResourceString(this, this.Name.ToString());
            common.RestoreFormLayOut(this.Name, this.layOut, this.grpHead);
            common.ReStoreLayOut(this.ListView, this.Name.ToString());

           


        }

        //打开文件
        void repProLotNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //取得要打开的文件名
            //显示制品LotNo信息
            DataRow dt = ListView.GetFocusedDataRow();
            string strFileName = "";
            if (dt != null)
            {
                strFileName = dt["picpath"].ToString();
            }

            if (System.IO.File.Exists(strFileName))
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = strFileName;
                process.StartInfo.Verb = "Open";
                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                process.Start();

            }
        }
        #endregion

        #region Grid选择按钮

        private void ListGrid_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                DoShowMenu(this.ListView.CalcHitInfo(new Point(e.X, e.Y)));
        }

        void DoShowMenu(DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hi)
        {

            if (hi.HitTest == DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitTest.ColumnButton)
            {
                common.subSelectData(ListGrid, ListView);
            }
        }
        #endregion

        #region 控件变化事件


        private void SetDeptDataSource()
        {
            //如果是制5课计划，则部门直接是制5课的
            //string strSQL = "SELECT DepartNo,DeptName FROM vie_SysUserDepartMent vsudm WHERE vsudm.UserId='" + this.txtUser.Text + "'";
             //2012-03-27需要给出所有的课别，因需要将制1，制2课分开打印
            string strSQL = "SELECT bdm.DeptNo,bdm.DeptName FROM BasDepartMent bdm \n"
                           + "WHERE bdm.DeptNo<>'D009'";
            this.lokDepart.Properties.DataSource = accessdb.GetRecord(strSQL).ADODataRst;
           
        }


        void lokDepart_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
           lookupeditProcess.LookUpEditProcessNewValue(sender, ref e);
            
        }

        void lokDepart_EditValueChanged(object sender, EventArgs e)
        {
            strDeptNo=this.lokDepart.Text;
            if (strDeptNo != "")
            {
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
                
                //根据最终部门显示批次号
                if (strDeptNo == "Z2" || strDeptNo=="Z3")
                    strDeptNo = "Z1";

                //设定版本号
                string strSQL = "SELECT DISTINCT o.TranNo FROM Operation" + strDeptNo + " o ORDER BY o.TranNo desc";
                DataTable dt = accessdb.GetRecord(strSQL).ADODataRst;
                this.lokPlanNo.Properties.DataSource = dt;
                if (dt.Rows.Count >= 1)
                {
                    this.lokPlanNo.Text = dt.Rows[0][0].ToString();
                    this.lokPlanNo.EditValue = dt.Rows[0][0].ToString();
                }
            }
            else
            {
                this.txtDepartName.Text = "";
                this.lokPlanNo.Properties.DataSource = null;
            }
        }

        private void lokDepart_TextChanged(object sender, EventArgs e)
        {
            if (this.lokDepart.Text != "")
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
            else
                this.txtDepartName.Text = "";
        }
        #endregion

        #region 工具栏按钮事件

        private void frmProcessCard_ToolButtonClick(object sender, string e)
        {
            try
            {
                switch (e)
                {
                    case "search":
                        if (!CheckData()) return;
                        SearchData();
                        break;
                    case "excel":
                        subExportXLS();
                        break;
                    case "exit":
                        common.SaveFormLayOut(this.Name  , this.layOut, this.grpHead);
                        common.SaveLayout(this.ListView, this.Name .ToString());
                        this.Dispose();
                        break;
                    case "import":
                        if(!subInsertData()) return;
                        //显示报表
                        ShowReport();
                        break;
                    case "print":
                        if (!subInsertData()) return;
                        //显示报表
                        PrintReport();
                        break;
                    default:
                        {
                            break;
                        }
                }


            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void ShowReport()
        {

            string strSQL = "SELECT * FROM vie_ProcessCard" + DeptNo + " where itemid='" + ItemID + "'";
            DataTable dtReport =accessdb.GetRecord(strSQL).ADODataRst;

            DevExpress.XtraReports.UI.XtraReport report = new DevExpress.XtraReports.UI.XtraReport();

            report = new rptProcessCard();
            report.Parameters["title"].Value = "制 程 识 别 卡";


            //报表相关参数设定
            report.Parameters["username"].Value = common._username;

            //报表显示
            ReportShow.ShowReport(report, true, dtReport);

        }

        private void PrintReport()
        {

            string strSQL = "SELECT * FROM vie_ProcessCard" + DeptNo + " where itemid='" + ItemID + "'";
            DataTable dtReport = accessdb.GetRecord(strSQL).ADODataRst;

            DevExpress.XtraReports.UI.XtraReport report = new DevExpress.XtraReports.UI.XtraReport();

            report = new rptProcessCard();
            report.PrintingSystem.ShowMarginsWarning = false;

            report.Parameters["title"].Value = "制 程 识 别 卡";


            //报表相关参数设定
            report.Parameters["username"].Value = common._username;

            //报表显示
           if(! ReportShow.ShowReport(report, false, dtReport)) return;

            //如果打印成功，则需要更新打印的次数
           strSQL = "exec pro_UpdatePrintCount" + DeptNo + " '" + ItemID + "'";
           accessdb.RsChange(strSQL);

        }

        private bool subInsertData()
        {
            if (!common.CheckExistsData(this.ListView)) return false;
            this.ListView.CloseEditor();
            this.ListView.UpdateCurrentRow();
            DataTable viewt = (DataTable)this.ListGrid.DataSource;
            DataRow[] drs = viewt.Select("chkSelect=1");
            if (drs.Length < 1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请至少选择一笔数据!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            //取出自动机判断制令量的数据     
            double projectUA = Convert.ToDouble(common.GetLanguageWord("PropertyID", "ProjectUser_UA"));

            //取出电脑机选择条件制令量
            double ProjectUser_UQTY = Convert.ToDouble(common.GetLanguageWord("PropertyID",  "ProjectUser_UQTY"));

            //取出电脑机选择条件制令量
            double ProjectUser_Price = Convert.ToDouble(common.GetLanguageWord("PropertyID", "ProjectUser_Price"));

            string tranNo = this.lokPlanNo.Text;
            ItemID = accessdb.GetField("SELECT CONVERT(VARCHAR(25),GETDATE(),121)").ToString();
            string strSqlInsert = " set xact_abort on begin tran "
                                    + "  insert into ProcessCardItem" + DeptNo
                                    + " select '" + tranNo + "',"
                                    + "code,getdate(),'" + ItemID + "'"
                                    + " from OrdersOut" + DeptNo + " where code in(";
            string stritemid = "";
            for (int row = 0; row < drs.Length; row++)
            {
                stritemid += "'" +  drs[row]["code"].ToString() + "',";
            }
            stritemid = stritemid.Substring(0, stritemid.Length - 1);
            strSqlInsert += stritemid + ")      ";

            strSqlInsert += " and tranno='" + tranNo + "'\n"
                           + " commit tran";
            if (!accessdb.RsChange(strSqlInsert)) return false;
            strSqlInsert = " EXEC pro_ProcessCard" + DeptNo + "\r\n"
                           + " @tranno ='" + tranNo + "', "
                           + " @ItemID ='" + ItemID + "', "
                           + " @ProjectUA = " + projectUA.ToString() + ",\r\n"
                           + " @ProjectUser_UQTY = " + ProjectUser_UQTY.ToString() + ",\r\n"
                           + " @projectUser_Uprice = " + ProjectUser_Price.ToString() + "\r\n";
            if (!accessdb.RsChange(strSqlInsert)) return false;
            return true;
        }
            
        private void subPrintReport()
        {
            DataTable dtSel = ((DataView)ListView.DataSource).Table;
            if (dtSel.Rows.Count <= 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("没有数据可供打印!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }

            DevExpress.XtraReports.UI.XtraReport report=new rptProcessCard();
           
            //报表相关参数设定
            report.Parameters["username"].Value = common._username;
            report.Parameters["title"].Value = common.sysParameter.ReportTitleZ1;
           
            //报表显示
            ReportShow.ShowReport(report, true, dtOrder);
          
        }


        private bool CheckData()
        {
            if (this.lokPlanNo.Text == "")
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("生产计划版本号不能为空，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.lokPlanNo.Focus();
                return false;
            }


            if (this.lokDepart.Text == "" )  
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("最终部门不能为空，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.lokDepart.Focus();
                return false;
            }



            return true;
        }



        private void subPrint()
        {
            if (!common.CheckExistsData(this.ListView)) return;
            common.PrintView(this.ListGrid, "计划数据");
        }

        private void subExportXLS()
        {
            try
            {
                if (!common.CheckExistsData(this.ListView)) return;
                common.ExportExcel(this.ListView);
                return;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void SearchData()
        {
            Cursor currentCursor = Cursor.Current;

            Cursor.Current = Cursors.WaitCursor;

            DeptNo = this.lokDepart.Text;
            if (DeptNo == "Z2")
                DeptNo = "Z1";

            //取得路径
            string filePath = common.GetLanguageWord("PropertyID", "ProjectUser_UDfolder").ToString();

            //根据选择的条件进行报表显示
            string strSQL = "select cast(0 as bit) as chkSelect ,  Code, ItemCode, dbo.GetShortDate( EST) est,"
                           + " dbo.GetShortDate( LET) let, Qty,  dbo.GetShortDate(starttime) starttime,"
                           + " dbo.GetShortDate(endtime) endtime,Spec1Code,CustomerCode,1 as showTZ,Spec2Code,bb.PrintCount,"  
                           //取得图片文件的名称
                           + "'" + filePath + "' + '\\'  + CustomerCode + '\\' +  REPLACE( replace(rtrim(Spec1Code),CHAR(13),''),CHAR(10),'') + '.pdf' as picPath,"
                            //2012-04-05显示订单的ChildCode字段中的第一个工序的资源代码，如果存在为空的资源，可能是工作没有导出来，导致找不到相关的工作
                           + " (SELECT DISTINCT oz.OperationMainResCode "
                           + " FROM Operation" + DeptNo + "  oz WHERE oz.TranNo=aa.TranNo AND   oz.ordercode=aa.Code "
                           + " and oz.procno=left(aa.childcode,2) ) Resource "

                           + " FROM OrdersOut" + DeptNo
                           + " aa left outer join ProcesCardPrint" + DeptNo + " bb  on aa.code=bb.MoNo"
                           + " where TranNo='" + this.lokPlanNo.Text + "'";

            if (strStartTime != "")
            {
                strSQL += " and dbo.getshortdate( strartTime)>='" + strStartTime + "'";

            }

            if (strEndTime != "")
            {
                strSQL += " and  dbo.getshortdate(strartTime)<='" + strEndTime + "'";

            }

            if (this.lokDepart.Text!="")
            {
                if (this.lokDepart.Text=="Z2")
                {
                    strSQL += " and  Spec2Code like '%2%' ";
                }
                else
                {
                    strSQL += " and  Spec2Code like '%" + this.lokDepart.Text.Substring(1, 1) + "%' and  Spec2Code not like '%2%'";
                }
            }
           
            dtOrder = accessdb.GetRecord(strSQL).ADODataRst;
            common.SubShowList(dtOrder, this.ListGrid, this.ListView, false);
            common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
            this.ListView.Columns[0].OptionsColumn.AllowEdit = true;
            this.ListView.Columns[0].OptionsColumn.AllowFocus = true;
            ListView.Columns[0].OptionsColumn.ReadOnly = false;
            this.ListGrid.Tag = 0;
            Cursor.Current = currentCursor;
 
        }



        #endregion

        //切换用户
        private void txtChange_Click(object sender, EventArgs e)
        {
            frmLogon frmLog = new frmLogon();
            frmLog.ShowDialog();

            if (frmLog.DialogResult == DialogResult.OK)
            {
                IniDataSource();
            }
           
            frmLog.Dispose();
            frmLog = null;

        }

        private void frmProcessCard_FormClosing(object sender, FormClosingEventArgs e)
        {
            serial.SerializeBinary(common.sysParameter, Application.StartupPath + @"\NNLInterface.dat");
            common._its_accessdb = null;
            common.pro = null;
            GC.Collect();
        }
    }
}
